package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.PhoenixUtil;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/3/10
 * DIM层处理主流和广播流数据，将维度数据过滤出来
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {

    private Map<String,TableProcess> mapConfig = new HashMap<>();

    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;

    public TableProcessFunction(MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //在声明周期开始的时候，从配置表中读取一次配置信息放到mapConfig中，从而解决主流数据先到而广播流没到的情况
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop202:3306/gmall0926_config?" +
            "user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        //获取数据库操作对象
        String sql = "select * from gmall0926_config.table_process where sink_type='dim'";
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行SQL
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        //处理结果集
        while(rs.next()){
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName,columnValue);
            }
            TableProcess tableProcess = jsonObj.toJavaObject(TableProcess.class);
            mapConfig.put(tableProcess.getSourceTable(),tableProcess);
        }

        //释放资源
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        //{"database":"gmall0926","xid":458,"data":{"tm_name":"三星1","logo_url":"/static/default.jpg","id":1},"old":{"tm_name":"三星"},"commit":true,"type":"update","table":"base_trademark","ts":1678498329}
        // System.out.println(jsonObj);
        //获取当前操作的业务数据库表的表名
        String tableName = jsonObj.getString("table");
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //根据表名获取对应的配置信息
        TableProcess tableProcess = null;

        if((tableProcess =  broadcastState.get(tableName)) != null ||(
            tableProcess =  mapConfig.get(tableName)) != null){
            //说明当前处理的业务表数据是维度数据 {"tm_name":"三星3","logo_url":"/static/default.jpg","id":1}
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

            //在向下游传递前，过滤掉不需要传递的属性 {"tm_name":"三星7","id":1}
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);

            //在向下游传递前，需要将输出的目的地补充上 {"tm_name":"三星3","sink_table":"dim_base_trademark","id":1}
            String sinkTable = tableProcess.getSinkTable();
            dataJsonObj.put("sink_table",sinkTable);

            //在向下游传递前，补充操作类型
            dataJsonObj.put("type",jsonObj.getString("type"));

            //将data-维度的变化内容传递到下游
            out.collect(dataJsonObj);
        }
    }

    //过滤掉不需要传递到下游的属性
    //dataJsonObj:  {"tm_name":"三星3","logo_url":"/static/default.jpg","id":1}
    //sinkColumns:  id,tm_name
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] fieldArr = sinkColumns.split(",");
        List<String> fieldList = Arrays.asList(fieldArr);

        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!fieldList.contains(entry.getKey()));
    }

    //"op":"r" : {"before":null,"after":{"source_table":"activity_info","source_type":"ALL","sink_table":"dim_activity_info","sink_type":"dim","sink_columns":"id,activity_name,activity_type,activity_desc,start_time,end_time,create_time","sink_pk":"id","sink_extend":null},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0926_config","sequence":null,"table":"table_process","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1678429765000,"transaction":null}
    //"op":"c" : {"before":null,"after":{"source_table":"a","source_type":"ALL","sink_table":"dim_a","sink_type":"dim","sink_columns":"id,name","sink_pk":"id","sink_extend":null},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1678429887000,"snapshot":"false","db":"gmall0926_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000011","pos":773930,"row":0,"thread":null,"query":null},"op":"c","ts_ms":1678429887821,"transaction":null}
    //"op":"u" : {"before":{"source_table":"a","source_type":"ALL","sink_table":"dim_a","sink_type":"dim","sink_columns":"id,name","sink_pk":"id","sink_extend":null},"after":{"source_table":"a","source_type":"ALL","sink_table":"dim_a","sink_type":"dim","sink_columns":"id,name,age","sink_pk":"id","sink_extend":null},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1678429924000,"snapshot":"false","db":"gmall0926_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000011","pos":774267,"row":0,"thread":null,"query":null},"op":"u","ts_ms":1678429924215,"transaction":null}
    //"op":"d" : {"before":{"source_table":"a","source_type":"ALL","sink_table":"dim_a","sink_type":"dim","sink_columns":"id,name,age","sink_pk":"id","sink_extend":null},"after":null,"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1678429966000,"snapshot":"false","db":"gmall0926_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000011","pos":774643,"row":0,"thread":null,"query":null},"op":"d","ts_ms":1678429966145,"transaction":null}
    //处理广播流数据
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        // System.out.println(jsonStr);
        //为了操作方便，将jsonStr转换为jsonObj
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        //获取操作类型
        String op = jsonObj.getString("op");
        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //判断对配置表做了什么样的操作
        if ("d".equals(op)) {
            //删除  将对应的配置信息从广播状态中删除掉
            //将删除的记录封装为TableProcess对象
            TableProcess before = jsonObj.getObject("before", TableProcess.class);
            //判断是不是删除了维度相关的配置
            String sinkType = before.getSinkType();
            if ("dim".equals(sinkType)) {
                //根据对象获取对应的表名
                String sourceTable = before.getSourceTable();
                //根据表名将配置信息从广播状态中删除掉
                broadcastState.remove(sourceTable);
                mapConfig.remove(sourceTable);
            }
        } else {
            //删除外的其它操作      将最新的配置信息封装为kv，放到广播状态中去
            //获取after对应的值
            TableProcess after = jsonObj.getObject("after", TableProcess.class);
            String sinkType = after.getSinkType();
            if ("dim".equals(sinkType)) {
                //获取业务数据库表名
                String sourceTable = after.getSourceTable();

                //获取Phoenix中维度表名字
                String sinkTable = after.getSinkTable();
                //获取表中的字段
                String sinkColumns = after.getSinkColumns();
                //获取建表主键
                String sinkPk = after.getSinkPk();
                //获取建表扩展语句
                String sinkExtend = after.getSinkExtend();

                //提前将维度表创建出来
                checkTable(sinkTable, sinkColumns, sinkPk, sinkExtend);

                //将读取的配置放到广播状态中
                broadcastState.put(sourceTable, after);
                mapConfig.put(sourceTable, after);
            }
        }
    }

    //创建维度表
    private void checkTable(String tableName, String sinkColumns, String pk, String ext) {
        if (pk == null) {
            pk = "id";
        }
        if (ext == null) {
            ext = "";
        }
        //拼接建表语句
        StringBuilder createSql = new StringBuilder("create table if not exists " + GmallConfig.PHOENIX_SCHEMA + "." + tableName + "(");
        //获取表中所有字段
        String[] columnArr = sinkColumns.split(",");
        for (int i = 0; i < columnArr.length; i++) {
            String columnName = columnArr[i];
            if (columnName.equals(pk)) {
                createSql.append(columnName + " varchar primary key");
            } else {
                createSql.append(columnName + " varchar ");
            }
            if (i < columnArr.length - 1) {
                createSql.append(",");
            }
        }
        createSql.append(") " + ext);
        System.out.println("在Phoenix中执行的建表语句：" + createSql);

        PhoenixUtil.executeSql(createSql.toString());

    }
}
